package com.ymatou.iapi.livemanage.testcase;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.ymatou.iapi.livemanage.service.CreateLiveCall;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.TestCase;
import com.ymt.utils.tag.P1;
import com.ymttest.business.service.AssertService;
import com.ymttest.business.service.LiveCallService;
import com.ymttest.business.service.NewJavaMongoCheckService;
import com.ymttest.database.model.AppCountry;
import com.ymttest.database.mongo.LiveBasicInfoWapper;
import com.ymttest.database.mongo.LiveModelWapper;
import com.ymttest.database.mongo.YmtMongoDriverFactroy;
import com.ymttest.database.mongo.jproduct.LivesWapper;
import com.ymttest.database.sqlwapper.AppCountryWapper;
import com.ymttest.database.sqlwapper.YmtLiveWapper;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.MapUtil;
import com.ymttest.utils.YMTDateUtil;

public class Ts_CreateActivity {
	private static int sellerId = Integer.parseInt(EnvSetup.getData("productsellerid"));
	private static String sellerName = EnvSetup.getData("productsellername");
	private static SimpleDateFormat TestSdf = new SimpleDateFormat("MMddHHmmss");
	private static CreateLiveCall createLiveCall;

	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("直播Admin-创建直播");
		createLiveCall = new CreateLiveCall();
	}

	@Before
	public void caseUp() {
	}

	@AfterClass
	public static void tearDown() {
		Logger.generateResult(createLiveCall.getOpurl());
	}

	public void getReturnCode(JSONObject dataStr) throws Exception {
		try {
			// 返回报文断言
			String code = dataStr.getString("Code");
			Logger.verifyIsContains(200, code, "\"Code\":200");
			String bCode = dataStr.getString("BCode");
			Logger.verifyIsContains(0, bCode, "\"BCode\":0");
			String msg = dataStr.getString("Msg");
			Logger.verifyIsNull(msg, "\"Msg\":为空");
			String trace = dataStr.getString("Trace");
			Logger.verifyIsNull(trace, "\"Trace\":为空");

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@After
	public void caseDown() {
		Logger.end();
	}

	
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_CreateActivity_001() {
		Logger.start(true, "创建直播(PC发布 - 未生效)");
		try {

			// update old live date
			LiveCallService.updateLiveDateAsBefore(sellerId);

			// live data
			Calendar c = Calendar.getInstance();
			String titleStr = "Title_" + TestSdf.format(c.getTime()); // 直播名称
			String nameStr = "Name_" + TestSdf.format(c.getTime()); // 扫货地名称
			String contentStr = "Content_" + TestSdf.format(c.getTime()); // 直播介绍
			int countryId = 0; // 美国
			int delType = 2;// 拼邮方式
			String picUrl = "http://p5.img.ymatou.com/upload/product/original/bbc1ec82986b4c3bada31797a3c29596_o.jpg";
			c.add(Calendar.DAY_OF_MONTH, 1);
			Date startDate = c.getTime();
			c.add(Calendar.HOUR, 2);
			Date endDate = c.getTime();
			String sVideoCover = "http://pc1.img.ymatou.com/G01/shangou/M00/29/4D/rBBlD1eV11GAQUVnAADlzWdoRYk576_n_w_o.jpg";
			String sVideoUrl = "http://ymatou-video.b0.upaiyun.com/uploads/20160725/92598b345ee25c56b6dda5d2271cd15f.mp4";
			String sPosition = "闸北";
			String strLatlng = "111,101";

			Map<String, Object> updateMap = new HashMap<String, Object>();
			updateMap.put("ActivityRequest->UserId", sellerId);
			updateMap.put("ActivityRequest->Title", titleStr);
			updateMap.put("ActivityRequest->ActivityName", nameStr);
			updateMap.put("ActivityRequest->ActivityContent", contentStr);
			updateMap.put("ActivityRequest->CountryId", countryId);
			updateMap.put("ActivityRequest->DelType", delType);
			updateMap.put("ActivityRequest->PicUrl", picUrl);
			updateMap.put("ActivityRequest->VideoCover", sVideoCover);
			updateMap.put("ActivityRequest->VideoUrl", sVideoUrl);
			updateMap.put("ActivityRequest->Position", sPosition);
			updateMap.put("ActivityRequest->IsFromPC", true);
			updateMap.put("ActivityRequest->AppConfirmed", false);
			updateMap.put("ActivityRequest->StartTime", LiveCallService.liveSDF.format(startDate));
			updateMap.put("ActivityRequest->EndTime", LiveCallService.liveSDF.format(endDate));
			updateMap.put("ActivityRequest->Latlng", strLatlng);

			// create live
			JSONObject result = createLiveCall.callAndGetReturnData(updateMap);
			JSONObject jsonBeanRequest = result.getJSONObject("JsonBeanRequest");

			// 获取国家
			// int countryId =
			// jsonBeanRequest.getJSONObject("ActivityRequest").getInt("CountryId");

			AppCountry appcountry = new AppCountryWapper().selectByCountryId(countryId).get(0);
			jsonBeanRequest.put("Country", appcountry.getScountrynamezh());
			jsonBeanRequest.put("Flag", appcountry.getSflag());

			// 报文断言
			getReturnCode(result);
			// 获取直播id
			int activityId = result.getJSONObject("Data").getInt("ActivityId");

			// 映射关系
			Map<String, String> sqlMap = sqlMap();
			sqlMap.put("ActivityRequest->Latlng", "sLatlng");
			Map<String, String> oldMongoMap = oldMongoMap();
			oldMongoMap.put("ActivityRequest->Latlng", "Latlng");
			Map<String, String> newMongoMap = newMongoMap();
			newMongoMap.put("ActivityRequest->Latlng", "Latlng");

			// 断言
			checkCreateActivity(activityId, jsonBeanRequest, sqlMap, oldMongoMap, newMongoMap,newJavaMongoMap(), startDate, endDate);

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_CreateActivity_002() {
		Logger.start(true, "创建直播(PC发布 - 已生效)");
		try {
			// update old live date
			LiveCallService.updateLiveDateAsBefore(sellerId);

			Calendar c = Calendar.getInstance();
			c.add(Calendar.DAY_OF_MONTH, 1);
			Date startTime = c.getTime();
			c.add(Calendar.HOUR, 2);
			Date endTime = c.getTime();

			Map<String, Object> updateMap = new HashMap<String, Object>();
			updateMap.put("ActivityRequest->UserId", sellerId);
			updateMap.put("ActivityRequest->StartTime", LiveCallService.liveSDF.format(startTime));
			updateMap.put("ActivityRequest->EndTime", LiveCallService.liveSDF.format(endTime));
			updateMap.put("ActivityRequest->IsFromPC", true);
			updateMap.put("ActivityRequest->AppConfirmed", true);

			// create live
			JSONObject result = createLiveCall.callAndGetReturnData(updateMap);
			JSONObject jsonBeanRequest = result.getJSONObject("JsonBeanRequest");

			// 获取国家
			int countryId = jsonBeanRequest.getJSONObject("ActivityRequest").getInt("CountryId");

			AppCountry appcountry = new AppCountryWapper().selectByCountryId(countryId).get(0);
			jsonBeanRequest.put("Country", appcountry.getScountrynamezh());
			jsonBeanRequest.put("Flag", appcountry.getSflag());

			// 报文断言
			getReturnCode(result);
			// 获取直播id
			int activityId = result.getJSONObject("Data").getInt("ActivityId");

			// 映射关系
			Map<String, String> sqlMap = sqlMap();
			Map<String, String> oldMongoMap = oldMongoMap();
			Map<String, String> newMongoMap = newMongoMap();

			// 断言
			checkCreateActivity(activityId, jsonBeanRequest, sqlMap, oldMongoMap, newMongoMap, newJavaMongoMap(),startTime, endTime);

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_CreateActivity_003() {
		Logger.start(true, "创建直播(APP发布 - 未生效)");
		try {
			// update old live date
			LiveCallService.updateLiveDateAsBefore(sellerId);

			Calendar c = Calendar.getInstance();
			c.add(Calendar.DAY_OF_MONTH, 1);
			Date startTime = c.getTime();
			c.add(Calendar.HOUR, 2);
			Date endTime = c.getTime();

			Map<String, Object> updateMap = new HashMap<String, Object>();
			updateMap.put("ActivityRequest->UserId", sellerId);
			updateMap.put("ActivityRequest->StartTime", LiveCallService.liveSDF.format(startTime));
			updateMap.put("ActivityRequest->EndTime", LiveCallService.liveSDF.format(endTime));
			updateMap.put("ActivityRequest->IsFromPC", false);
			updateMap.put("ActivityRequest->AppConfirmed", false);

			// create live
			JSONObject result = createLiveCall.callAndGetReturnData(updateMap);
			JSONObject jsonBeanRequest = result.getJSONObject("JsonBeanRequest");

			// 获取国家
			int countryId = jsonBeanRequest.getJSONObject("ActivityRequest").getInt("CountryId");

			AppCountry appcountry = new AppCountryWapper().selectByCountryId(countryId).get(0);
			jsonBeanRequest.put("Country", appcountry.getScountrynamezh());
			jsonBeanRequest.put("Flag", appcountry.getSflag());

			// 报文断言
			getReturnCode(result);
			// 获取直播id
			int activityId = result.getJSONObject("Data").getInt("ActivityId");

			// 映射关系
			Map<String, String> sqlMap = sqlMap();
			Map<String, String> oldMongoMap = oldMongoMap();
			Map<String, String> newMongoMap = newMongoMap();

			// 断言
			checkCreateActivity(activityId, jsonBeanRequest, sqlMap, oldMongoMap, newMongoMap,newJavaMongoMap(), startTime, endTime);

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_CreateActivity_004() {
		Logger.start(true, "创建直播(APP发布 - 已生效)");
		try {
			// update old live date
			LiveCallService.updateLiveDateAsBefore(sellerId);

			Calendar c = Calendar.getInstance();
			c.add(Calendar.DAY_OF_MONTH, 1);
			Date startTime = c.getTime();
			c.add(Calendar.HOUR, 2);
			Date endTime = c.getTime();

			Map<String, Object> updateMap = new HashMap<String, Object>();
			updateMap.put("ActivityRequest->UserId", sellerId);
			updateMap.put("ActivityRequest->StartTime", LiveCallService.liveSDF.format(startTime));
			updateMap.put("ActivityRequest->EndTime", LiveCallService.liveSDF.format(endTime));
			updateMap.put("ActivityRequest->IsFromPC", false);
			updateMap.put("ActivityRequest->AppConfirmed", true);

			// create live
			JSONObject result = createLiveCall.callAndGetReturnData(updateMap);
			JSONObject jsonBeanRequest = result.getJSONObject("JsonBeanRequest");

			// 获取国家
			int countryId = jsonBeanRequest.getJSONObject("ActivityRequest").getInt("CountryId");

			AppCountry appcountry = new AppCountryWapper().selectByCountryId(countryId).get(0);
			jsonBeanRequest.put("Country", appcountry.getScountrynamezh());
			jsonBeanRequest.put("Flag", appcountry.getSflag());

			// 报文断言
			getReturnCode(result);
			// 获取直播id
			int activityId = result.getJSONObject("Data").getInt("ActivityId");

			// 映射关系
			Map<String, String> sqlMap = sqlMap();
			Map<String, String> oldMongoMap = oldMongoMap();
			Map<String, String> newMongoMap = newMongoMap();

			// 断言
			checkCreateActivity(activityId, jsonBeanRequest, sqlMap, oldMongoMap, newMongoMap, newJavaMongoMap(),startTime, endTime);

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_CreateActivity_005() {
		Logger.start(true, "创建直播(APP发布 - 已生效)");
		try {
			// update old live date
			LiveCallService.updateLiveDateAsBefore(sellerId);

			Calendar c = Calendar.getInstance();
			c.add(Calendar.DAY_OF_MONTH, 1);
			Date startTime = c.getTime();
			c.add(Calendar.HOUR, 2);
			Date endTime = c.getTime();

			Map<String, Object> updateMap = new HashMap<String, Object>();
			updateMap.put("ActivityRequest->UserId", sellerId);
			updateMap.put("ActivityRequest->StartTime", LiveCallService.liveSDF.format(startTime));
			updateMap.put("ActivityRequest->EndTime", LiveCallService.liveSDF.format(endTime));
			updateMap.put("ActivityRequest->IsFromPC", false);
			updateMap.put("ActivityRequest->AppConfirmed", true);

			// create live
			JSONObject result = createLiveCall.callAndGetReturnData(updateMap);
			JSONObject jsonBeanRequest = result.getJSONObject("JsonBeanRequest");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	/**
	 * sql映射关系
	 * 
	 * @return
	 * @throws Exception
	 */
	public Map<String, String> sqlMap() throws Exception {
		try {
			Map<String, String> sqlMap = new HashMap<String, String>();
			sqlMap.put("ActivityRequest->CountryId", "iCountryId");
			sqlMap.put("ActivityRequest->ActivityName", "sName");
			sqlMap.put("ActivityRequest->Position", "sPosition");
			sqlMap.put("ActivityRequest->Title", "sTitle");
			sqlMap.put("ActivityRequest->ActivityContent", "sContent");
			sqlMap.put("ActivityRequest->VideoCover", "sVideoCover");
			sqlMap.put("ActivityRequest->VideoUrl", "sVideoUrl");
			sqlMap.put("ActivityRequest->AppConfirmed", "bAppConfirmed");
			sqlMap.put("ActivityRequest->UserId", "iSellerId");
			sqlMap.put("ActivityRequest->IsFromPC", "bIsFromPC");
			sqlMap.put("ActivityRequest->PicUrl", "sPicUrl");
			sqlMap.put("ActivityRequest->DelType", "iDeliveryType");
			sqlMap.put("ActivityRequest->Action", "iAction");
			return sqlMap;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * oldMongo映射关系(主动缓存老库)
	 * 
	 * @return
	 * @throws Exception
	 */
	public Map<String, String> oldMongoMap() throws Exception {
		try {
			Map<String, String> oldMongoMap = new HashMap<String, String>();
			oldMongoMap.put("ActivityRequest->ActivityName", "ActivityName");
			oldMongoMap.put("ActivityRequest->Position", "ShopAddress");
			oldMongoMap.put("ActivityRequest->Title", "Title");
			oldMongoMap.put("ActivityRequest->ActivityContent", "ActivityContent");
			oldMongoMap.put("ActivityRequest->VideoCover", "VideoCover");
			oldMongoMap.put("ActivityRequest->VideoUrl", "VideoUrl");
			oldMongoMap.put("ActivityRequest->AppConfirmed", "AppConfirmed");
			oldMongoMap.put("ActivityRequest->UserId", "SellerId");
			oldMongoMap.put("ActivityRequest->PicUrl", "ActivityPicture");
			oldMongoMap.put("ActivityRequest->Action", "Action");
			oldMongoMap.put("Country", "Country");
			oldMongoMap.put("Flag", "Flag");
			return oldMongoMap;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * newMongo映射关系(主动缓存老库)
	 * 
	 * @return
	 * @throws Exception
	 */
	public Map<String, String> newMongoMap() throws Exception {
		try {
			Map<String, String> newMongoMap = new HashMap<String, String>();
			newMongoMap.put("ActivityRequest->ActivityName", "ActivityName");
			newMongoMap.put("ActivityRequest->Position", "ShopAddress");
			newMongoMap.put("ActivityRequest->Title", "Title");
			newMongoMap.put("ActivityRequest->ActivityContent", "ActivityContent");
			newMongoMap.put("ActivityRequest->VideoCover", "VideoCover");
			newMongoMap.put("ActivityRequest->VideoUrl", "VideoUrl");
			newMongoMap.put("ActivityRequest->AppConfirmed", "AppConfirmed");
			newMongoMap.put("ActivityRequest->UserId", "SellerId");
			newMongoMap.put("ActivityRequest->PicUrl", "ActivityPicture");
			newMongoMap.put("ActivityRequest->Action", "Action");
			newMongoMap.put("Country", "Country");
			newMongoMap.put("Flag", "Flag");
			return newMongoMap;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * newJavaMongo映射关系(主动缓存老库)
	 * 
	 * @return
	 * @throws Exception
	 */
	public Map<String, String> newJavaMongoMap() throws Exception {
		try {
			Map<String, String> newMongoMap = new HashMap<String, String>();
			newMongoMap.put("ActivityRequest->ActivityName", "name");
			newMongoMap.put("ActivityRequest->Position", "addr");
			newMongoMap.put("ActivityRequest->Title", "title");
			newMongoMap.put("ActivityRequest->ActivityContent", "content");
			newMongoMap.put("ActivityRequest->VideoCover", "vcover");
			newMongoMap.put("ActivityRequest->VideoUrl", "vurl");
			newMongoMap.put("ActivityRequest->AppConfirmed", "confirm");
			newMongoMap.put("ActivityRequest->UserId", "sid");
			newMongoMap.put("ActivityRequest->PicUrl", "pic");
			newMongoMap.put("ActivityRequest->Action", "action");
			newMongoMap.put("ActivityRequest->Latlng", "latlng");
			return newMongoMap;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 断言方法
	 * 
	 * @param activityId
	 *            直播id
	 * @param jsonBeanRequest
	 *            请求报文
	 * @param sqlMap
	 *            SQL断言映射关系
	 * @param oldMongoMap
	 *            mongo老库断言映射关系
	 * @param newMongoMap
	 *            mongo新库断言映射关系
	 * @param startTime
	 *            直播开始时间
	 * @param endTime
	 *            直接结束时间
	 * @throws Exception
	 */
	public void checkCreateActivity(int activityId, JSONObject jsonBeanRequest, Map<String, String> sqlMap,
			Map<String, String> oldMongoMap, Map<String, String> newMongoMap, Date startTime, Date endTime) {
		
		checkCreateActivity(activityId, jsonBeanRequest, sqlMap, oldMongoMap, newMongoMap, null, startTime, endTime);
	}

	/**
	 * 断言方法
	 * 
	 * @param activityId
	 *            直播id
	 * @param jsonBeanRequest
	 *            请求报文
	 * @param sqlMap
	 *            SQL断言映射关系
	 * @param oldMongoMap
	 *            mongo老库断言映射关系
	 * @param newMongoMap
	 *            mongo新库断言映射关系
	 * @param newJavaMongoMap
	 *            mongo新库断言映射关系
	 * @param startTime
	 *            直播开始时间
	 * @param endTime
	 *            直接结束时间
	 * @throws Exception
	 */
	public void checkCreateActivity(int activityId, JSONObject jsonBeanRequest, Map<String, String> sqlMap,
			Map<String, String> oldMongoMap, Map<String, String> newMongoMap, Map<String, String> newJavaMongoMap,
			Date startTime, Date endTime) {

		try {

			// SQL
			List<Map> productsInActivity = (List<Map>) new YmtLiveWapper().selectforMapByLiveId(activityId);
			HashMap<String, Object> actRetMapbysql = (HashMap<String, Object>) productsInActivity.get(0);
			// SQL断言
			AssertService.assertResultEqual(sqlMap, jsonBeanRequest, actRetMapbysql);

			// SQL时间对比
			Map<String, Object> ret = MapUtil.pojoToMap(new YmtLiveWapper().selectByLiveId(activityId));
			AssertService.assertTime(startTime, (Date) ret.get("dbegintime"), 40);
			AssertService.assertTime(endTime, (Date) ret.get("dendtime"), 40);

			if (YmtMongoDriverFactroy.isOldMongoCheck()) {

				// old Mongo
				Map<String, Object> liveBasicInfoMap = new LiveBasicInfoWapper().getActivityId(activityId);
				// 断言
				AssertService.assertResultEqual(oldMongoMap, jsonBeanRequest, liveBasicInfoMap);

				AssertService.assertTime(startTime, (Date) liveBasicInfoMap.get("StartTime"), 40);
				AssertService.assertTime(endTime, (Date) liveBasicInfoMap.get("EndTime"), 41);
				AssertService.assertTime(YMTDateUtil.getDate(), (Date) liveBasicInfoMap.get("AddTime"), 1000);

			}

			if (YmtMongoDriverFactroy.isNewMongoCheck()) {

				// Mongo 新库
				LiveModelWapper liveModelWapper = new LiveModelWapper();
				Logger.verifyEquals(1, liveModelWapper.getCountByActivityId(activityId), "活动数据应该只有1条");
				Map<String, Object> liveModelMap = liveModelWapper.getActivityId(activityId);

				AssertService.assertResultEqual(newMongoMap, jsonBeanRequest, liveModelMap);

				AssertService.assertTime(startTime, (Date) liveModelMap.get("StartTime"), 42);
				AssertService.assertTime(endTime, (Date) liveModelMap.get("EndTime"), 43);
				AssertService.assertTime(YMTDateUtil.getDate(), (Date) liveModelMap.get("AddTime"), 1000);

			}

			if (YmtMongoDriverFactroy.isNewJavaMgoCheck()) {
				// Java Mongo 新库检查
				LivesWapper livesWapper = new LivesWapper();
				Logger.verifyEquals(1, livesWapper.getCountByActivityId(activityId), "活动数据应该只有1条");
				Map<String, Object> liveModelMap = livesWapper.getByActivityId(activityId);

				// 请求中数据检查
				AssertService.assertResultEqual(newJavaMongoMap, jsonBeanRequest, liveModelMap, "Mongo-Lives");

				// 时间检查
				AssertService.assertTime(startTime, (Date) liveModelMap.get("start"), 42);
				AssertService.assertTime(endTime, (Date) liveModelMap.get("end"), 43);
				AssertService.assertTime(YMTDateUtil.getDate(), (Date) liveModelMap.get("add"), 1000);

				// 其他数据检查
				int userId = Integer.parseInt(liveModelMap.get("sid").toString());
				String userName = LiveCallService.getLoginUserName(userId);

				// 获取国家
				int countryId = jsonBeanRequest.getJSONObject("ActivityRequest").getInt("CountryId");

				AppCountry appcountry = new AppCountryWapper().selectByCountryId(countryId).get(0);
				String countryStr = appcountry.getScountrynamezh();
				String flagStr = appcountry.getSflag();

				Map<String, Object> otherMap = MapUtil.hashMap("sname", userName, "country", countryStr, "flag",
						flagStr);
				AssertService.assertResultEqual(otherMap, liveModelMap, "Mongo-Lives");

				// brands
				// 检查品牌
				JSONArray tgtAry = new JSONArray(LiveCallService.getProdBrandsInLive(activityId));
				if (tgtAry.length()==0){
					Logger.verifyIsNull(liveModelMap.get("brands"), "Mongo-Lives,compare with Sql");
				}else{
					JSONArray actAry = new JSONArray(liveModelMap.get("brands").toString());
					AssertService.checkArray(tgtAry, actAry);
				}
				
				
				//check from sql
				NewJavaMongoCheckService.checkLiveMgoSyncBySQL_NewJavaMgo(activityId);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
